package com.hzjq.encrypt.util

import android.content.Context
import android.media.MediaScannerConnection
import android.os.Environment
import android.webkit.MimeTypeMap
import java.io.*


class FileStreamX {
    companion object {

        fun read(inputStream: InputStream): String {
            var inputStreamReader: InputStreamReader? = null
            try {
                inputStreamReader = InputStreamReader(inputStream, "utf-8")
            } catch (e1: UnsupportedEncodingException) {
                e1.printStackTrace()
            }
            val reader = BufferedReader(inputStreamReader)
            val sb = StringBuffer("")
            var line: String?
            try {
                while (reader.readLine().also { line = it } != null) {
                    sb.append(line)
                    sb.append("\n")
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return sb.toString()
        }

        fun write(json: String, filePath: String): Boolean {
            try {
                val file = File(filePath)
                if (!file.exists()) {
                    // val dir = File(file.parent)
                    //val mkdirs = dir.mkdirs()

                    val createNewFile = file.createNewFile()
                    ELog.e("file:${file.absolutePath} createNewFile:${createNewFile}")
                }

                val outStream = FileOutputStream(file)
                outStream.write(json.toByteArray())
                outStream.close()
                return true
            } catch (e: Exception) {
                e.printStackTrace()
                return false
            }
        }

        fun getOutDir(context: Context): String {

//            val externalFilesDirs = context.getExternalFilesDir(null) ?: return ""
//            val path = (externalFilesDirs.absolutePath ?: "") + File.separator.toString() + "encrypt"
//            val path = Environment.getExternalStorageDirectory().absolutePath+ File.separator.toString() + "encrypt"
            val hasSDCard = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
            val path = if (hasSDCard) {
                Environment.getExternalStorageDirectory().getPath()
                    .toString() + File.separator.toString() + "encrypt"
            } else Environment.getDownloadCacheDirectory()
                .toString() + File.separator.toString() + "encrypt"


            if (!File(path).exists()) {
                val mkdirs = File(path).mkdirs()
                ELog.e("mkdirs ${path} $mkdirs")
            }

            return path
        }

        fun refresh(context: Context) {
            val path = getOutDir(context)
            MediaScannerConnection.scanFile(
                context, arrayOf(path),
                arrayOf(MimeTypeMap.getSingleton().toString())
            ) { path, uri ->

            }
        }
    }
}